//
//  IpList1Controller.m
//  PeaPodAgent
//
//  Created by MasterLing on 2018/4/12.
//  Copyright © 2018年 MasterLing. All rights reserved.
//

#import "IpListController.h"
#import "IpListReusableView.h"
#import "UIView+TapGestureRecognizer.h"
//#import "XMGroupModel.h"
//#import "XMChildModel.h"
#import "IpListCollectionCell.h"
#import "RandomView.h"
#import <PYSearch/PYSearchViewController.h>
#import "ProvinceModel.h"
#import "CityModel.h"



static NSString *const ReusableViewID = @"IpListReusableView";
static NSString *const CollectionCellID = @"IpListCollectionCell";

static const CGFloat kItemHeight = 40.0f;


@interface IpListController ()<UICollectionViewDelegate, UICollectionViewDataSource,IpListReusableViewDelegate,PYSearchViewControllerDelegate>

@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) NSMutableArray *dataSourceArray;

@property (nonatomic, strong) NSMutableArray *hotSearchArray;

@property (nonatomic, strong) NSMutableArray *totalCityArray;

@end

@implementation IpListController


- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"线路选择";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"sousuo"] style:UIBarButtonItemStylePlain target:self action:@selector(pySearchWithHot)];
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(kScreenW/2.0, kItemHeight);
    layout.minimumLineSpacing = 0.0;
    layout.minimumInteritemSpacing = 0.0;
    layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    layout.headerReferenceSize = CGSizeMake(self.view.frame.size.width, 50);
    self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout];
    self.collectionView.contentInset = UIEdgeInsetsMake(62, 0, 0, 0);
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = [UIColor hexStringToColor:@"f6f7f9"];
    self.collectionView.showsVerticalScrollIndicator = NO;
    
    [self.collectionView registerNib:[UINib nibWithNibName:CollectionCellID bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:CollectionCellID];
    [self.collectionView registerNib:[UINib nibWithNibName:ReusableViewID bundle:[NSBundle mainBundle]] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:ReusableViewID];
    [self.view addSubview:self.collectionView];
    [self requestDataSource];
    
    RandomView *randomView = [[NSBundle mainBundle] loadNibNamed:@"RandomView" owner:nil options:nil].lastObject;
    randomView.frame = CGRectMake(0, -62, kScreenW, 62);
    [self.collectionView addSubview:randomView];
    
}

- (NSMutableArray *)dataSourceArray {
    if (!_dataSourceArray) {
        _dataSourceArray = [NSMutableArray array];
    }
    return _dataSourceArray;
}

- (NSMutableArray *)totalCityArray {
    if (!_totalCityArray) {
        _totalCityArray = [NSMutableArray array];
    }
    return _totalCityArray;
}

- (void) requestDataSource {
    NSDictionary *paraments = @{@"page":@"0"};
    [NetWorkManager requestWithType:HttpRequestTypePost withUrlString:@"api/server/android-dynamic-server" withParaments:paraments withSuccessBlock:^(NSDictionary *object) {
        if ([[object valueForKey:@"code"] integerValue] == STATUS_OK) {
            NSArray *dataArray = [object objectForKey:@"data"];
            [dataArray enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                ProvinceModel *province = [[ProvinceModel alloc] init];
                province.NAME = [obj objectForKey:@"NAME"];
                province.ParentId = [[obj objectForKey:@"ParentId"] integerValue];
                province.LevelType = [[obj objectForKey:@"LevelType"] integerValue];
                province.open = false;
                NSArray *cityArray = [obj objectForKey:@"server_list"];
                [cityArray enumerateObjectsUsingBlock:^(NSDictionary *  _Nonnull city, NSUInteger idx, BOOL * _Nonnull stop) {
                    CityModel *cityModel = [[CityModel alloc] init];
                    cityModel.server_id = [[city objectForKey:@"id"] integerValue];
                    cityModel.server_name = [city objectForKey:@"server_name"];
//                    [[DataBase sharedDataBase] insertCity:cityModel];
                    [province.cityModels addObject:cityModel];
                    [self.totalCityArray addObject:cityModel];
                    if ([[city objectForKey:@"is_hot"] integerValue] == 1) {
                        [self.hotSearchArray addObject:cityModel.server_name];
                    }
                }];
                [self.dataSourceArray addObject:province];
            }];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.collectionView reloadData];
            });
        }
    } withFailureBlock:^(NSError *error) {
        
    } progress:^(float progress) {
        
    }];
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.dataSourceArray.count;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    ProvinceModel *province = self.dataSourceArray[section];
    if (province.isOpen) {
        return province.cityModels.count;
    }else{
        return 0;
    }
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    IpListCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CollectionCellID forIndexPath:indexPath];
    ProvinceModel *province = self.dataSourceArray[indexPath.section];
    cell.cityModel = province.cityModels[indexPath.item];
    return cell;
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if (![kind isEqualToString:UICollectionElementKindSectionHeader]) {
        return nil;
    }
    IpListReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:ReusableViewID forIndexPath:indexPath];
    headerView.provinceModel = self.dataSourceArray[indexPath.section];
    headerView.delegate   = self;
    return headerView;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    ProvinceModel *province = self.dataSourceArray[indexPath.section];
    CityModel *city = province.cityModels[indexPath.item];
    NSString *server_id = [NSString stringWithFormat:@"%ld",(long)city.server_id];
    [[NSUserDefaults standardUserDefaults] setObject:server_id forKey:@"CitySelect"];
    [[NSUserDefaults standardUserDefaults] setObject:city.server_name forKey:@"server_name"];
    [[NSNotificationCenter defaultCenter] postNotificationName:KKCitySelectNotification object:nil];
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void) headerViewClicked:(IpListReusableView *)headerView {
    [self.collectionView reloadData];
}

- (NSMutableArray *)hotSearchArray{
    if (!_hotSearchArray) {
        _hotSearchArray = [NSMutableArray array];
        [_hotSearchArray addObject:@"徐州电信"];
        [_hotSearchArray addObject:@"南京电信"];
//        NSMutableArray *dataArray = [[DataBase sharedDataBase] queryHotCity];
//        [dataArray enumerateObjectsUsingBlock:^(CityModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//            [_hotSearchArray addObject:obj.server_name];
//        }];
    }
    return _hotSearchArray;
}


#pragma mark - actions
- (void) pySearchWithHot {
    PYSearchViewController *searchViewController = [PYSearchViewController searchViewControllerWithHotSearches:self.hotSearchArray searchBarPlaceholder:@"支持中文、拼音搜索" didSearchBlock:^(PYSearchViewController *searchViewController, UISearchBar *searchBar, NSString *searchText) {
        searchText = [searchText stringByReplacingOccurrencesOfString:@" " withString:@""];
        [self.totalCityArray enumerateObjectsUsingBlock:^(CityModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj.server_name isEqualToString:searchText]||[[obj.server_name stringByReplacingOccurrencesOfString:@" " withString:@""] isEqualToString:searchText]) {
                NSString *server_id = [NSString stringWithFormat:@"%ld",(long)obj.server_id];
                [[NSUserDefaults standardUserDefaults] setObject:server_id forKey:@"CitySelect"];
                [[NSNotificationCenter defaultCenter] postNotificationName:KKCitySelectNotification object:nil];
            }
            [self.navigationController dismissViewControllerAnimated:YES completion:nil];
            [self.navigationController popViewControllerAnimated:YES];
        }];
    }];
    [searchViewController.searchBar setSearchFieldBackgroundImage:[UIImage imageNamed:@"fieldBackImage"] forState:UIControlStateNormal];
    searchViewController.hotSearchStyle = PYHotSearchStyleBorderTag;
    searchViewController.cancelButton.tintColor = [UIColor hexStringToColor:@"#666666"];
    searchViewController.searchHistoryStyle = PYSearchHistoryStyleBorderTag;
    searchViewController.hotSearchTitle = NSLocalizedString(@"热门推荐", nil);
    searchViewController.searchHistoryTitle = NSLocalizedString(@"搜索记录", nil);
    searchViewController.delegate = self;
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:searchViewController];
    [self presentViewController:nav  animated:NO completion:nil];
}

#pragma mark - PYSearchViewControllerDelegate
- (void)searchViewController:(PYSearchViewController *)searchViewController searchTextDidChange:(UISearchBar *)seachBar searchText:(NSString *)searchText
{
    if (searchText.length) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            NSMutableArray *searchSuggestionsM = [NSMutableArray array];
            for (CityModel *city in self.totalCityArray) {
                NSString *city_name = city.server_name;
                if ([city_name rangeOfString:searchText options:NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch].location != NSNotFound) {
                    [searchSuggestionsM addObject:city_name];
                }
            }
            searchViewController.searchSuggestions = searchSuggestionsM;
        });
    }
}


@end
